// packageX/auditor_management/auditor_management.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    verifiers: [],
    districtId: '',
    searchKeyword: '',
    pageNum: 1,
    pageSize: 10,
    hasMore: true,
    loading: false,
    showAddPopup: false,
    // 搜索会员相关
    memberSearchKeyword: '',
    memberList: [],
    memberLoading: false,
    selectedMember: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getVerifierList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      pageNum: 1,
      hasMore: true,
      verifiers: []
    });
    this.getVerifierList();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({
        pageNum: this.data.pageNum + 1
      });
      this.getVerifierList();
    }
  },

  /**
   * 获取核销员列表
   */
  getVerifierList() {
    if (this.data.loading) return;
    
    this.setData({
      loading: true
    });
    
    let that = this;
    
    // 调用真实接口获取核销员列表
    let urlStr = app.getNetAddresss("plugin.commerce.api.commerce-activity.get-auditor-list");
    app._getNetWork({
      url: urlStr,
      data: {
        page: this.data.pageNum,
        pageSize: this.data.pageSize,
      },
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let newVerifiers = res.data.list || [];
          const allVerifiers = that.data.pageNum === 1 ? newVerifiers : [...that.data.verifiers, ...newVerifiers];
          
          that.setData({
            verifiers: allVerifiers,
            hasMore: newVerifiers.length === that.data.pageSize
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function(res) {
        console.log('获取核销员列表失败:', res);
        wx.showToast({
          icon: 'none',
          title: '获取数据失败',
          duration: 1500
        });
      },
      complete: function() {
        that.setData({
          loading: false
        });
      }
    });
  },

  /**
   * 搜索输入
   */
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
    this.setData({
      pageNum: 1,
      hasMore: true,
      verifiers: []
    });
    this.getVerifierList();
  },

  /**
   * 打开新增核销员弹窗
   */
  onAddVerifierTap() {
    this.setData({
      showAddPopup: true,
      newVerifierName: '',
      newVerifierPhone: ''
    });
  },

  /**
   * 关闭新增审核员弹窗
   */
  onCloseAddPopup() {
    this.setData({
      showAddPopup: false
    });
  },

  /**
   * 搜索会员输入
   */
  onMemberSearchInput(e) {
    const keyword = e.detail.value;
    this.setData({
      memberSearchKeyword: keyword
    });
    
    // 搜索关键词至少2个字符才发起请求
    if (keyword.length >= 1) {
      this.searchMembers(keyword);
    } else {
      this.setData({
        memberList: []
      });
    }
  },

  /**
   * 搜索会员
   */
  searchMembers(keyword) {
    if (this.data.memberLoading) return;
    
    this.setData({
      memberLoading: true
    });
    
    let that = this;
    // 调用搜索会员接口
    let urlStr = app.getNetAddresss("plugin.commerce.api.commerce-member.search-auditors");
    app._getNetWork({
      url: urlStr,
      data: {
        keyword: keyword,
        page: 1,
        pageSize: 10
      },
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            memberList: res.data.result || []
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function(res) {
        console.log('搜索会员失败:', res);
        wx.showToast({
          icon: 'none',
          title: '搜索失败，请重试',
          duration: 1500
        });
      },
      complete: function() {
        that.setData({
          memberLoading: false
        });
      }
    });
  },

  /**
   * 选择会员并添加为核销员
   */
  selectMember(e) {
    const uid = e.currentTarget.dataset.uid;
    
    wx.showLoading({ title: '处理中' });
    
    let that = this;
    // 调用添加核销员接口
    let urlStr = app.getNetAddresss("plugin.commerce.api.commerce-activity.add-auditor");
    app._postNetWork({
      url: urlStr,
      data: {
        verifier_id: uid
      },
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            title: '新增成功',
            icon: 'success'
          });
          // 重新获取核销员列表
          that.setData({
            showAddPopup: false,
            pageNum: 1,
            hasMore: true,
            verifiers: []
          });
          that.getVerifierList();
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function(res) {
        console.log('新增核销员失败:', res);
        wx.showToast({
          icon: 'none',
          title: '操作失败，请重试',
          duration: 1500
        });
      },
      complete: function() {
        wx.hideLoading();
      }
    });
  },

  /**
   * 删除核销员
   */
  onDeleteVerifierTap(e) {
    const { id, name } = e.currentTarget.dataset;
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除核销员"${name}"吗？`,
      showCancel: true,
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '处理中' });
          
          let that = this;
          // 调用真实接口删除核销员
          let urlStr = app.getNetAddresss("plugin.commerce.api.commerce-activity.delete-auditor");
          app._postNetWork({
            url: urlStr,
            data: {
              id: id
            },
            success: function(resdata) {
              var res = resdata.data;
              if (res.result == 1) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success'
                });
                // 重新获取核销员列表
                that.setData({
                  pageNum: 1,
                  hasMore: true,
                  verifiers: []
                });
                that.getVerifierList();
              } else {
                wx.showToast({
                  icon: 'none',
                  title: res.msg,
                  duration: 1500
                });
              }
            },
            fail: function(res) {
              console.log('删除核销员失败:', res);
              wx.showToast({
                icon: 'none',
                title: '操作失败，请重试',
                duration: 1500
              });
            },
            complete: function() {
              wx.hideLoading();
            }
          });
        }
      }
    });
  }
});